package com.terren.statistic.common.util;

public class StringUtil {
    private static int MYSQL_TINY_TEXT_LENGTH = (2 << 7) - 1;
    private static int MYSQL_TEXT_LENGTH = (2 << 15) - 1;
    private static int MYSQL_MEDIUM_TEXT_LENGTH = (2 << 23) - 1;
    private static int MYSQL_LONG_TEXT_LENGTH = (2 << 31) - 1;

    /*
     * 以UTF8编码格式截取字符串用于MySQL存储
     * UTF-8 规范参考  http://en.wikipedia.org/wiki/UTF-8
     */
    public static String truncate(String s, int maxBytes) {
    	if(s == null)
    		return "";
        int b = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            int skip = 0;
            int left;
            if (c <= 0x007f) {
                left = 1;
            }
            else if (c <= 0x07FF) {
                left = 2;
            } else if (c <= 0xd7ff) {
                left = 3;
            } else if (c <= 0xDFFF) {
                left = 4;
                skip = 1;
            } else {
                left = 3;
            }
            if (b + left > maxBytes) {
                return s.substring(0, i);
            }
            b += left;
            i += skip;
        }
        return s;
    }

    public static String truncateAsText(String s) {
        return truncate(s, MYSQL_TEXT_LENGTH);
    }

    public static String truncateAsTinyText(String s) {
        return truncate(s, MYSQL_TINY_TEXT_LENGTH);
    }

    public static String truncateAsMediumText(String s) {
        return truncate(s, MYSQL_MEDIUM_TEXT_LENGTH);
    }

    public static String truncateAsLongText(String s) {
        return truncate(s, MYSQL_LONG_TEXT_LENGTH);
    }
}
